import React,{useState} from 'react'
import "./Choice.less"
import ChoiceItem from "../Choiceitem/Choiceitem"
import Button from '@mui/material/Button';
 import {Getput} from "@/request/api"

  
export default function Choice({data}:IProps) {
  const questionType:IQusType={
    many:"多选",
    one:"单选",
    check:"判断",
    code:"编程"
  }
  let [ischeck,setCheck] = useState<string[]>([])
  let [Msg,setmsg] = useState("")
//  选项
const options:IOption[] = JSON.parse(data.optionContent)

const oncheck = (val:string)=>{
  console.log(val);
  if(data.questionType === "many"){
    // 判断是不是点过了:当前点击的这个选项val是不是已经在ischeck数组里
    if(ischeck.includes(val)){
      // 如果在  取消  数组截取
      // 数组.splice(从哪开始,截取几个)
      let idd = ischeck.indexOf(val)
      ischeck.splice(idd,1)
      setCheck([...ischeck])
    }else{
      // 不在 追加
      // push
      setCheck([...ischeck,val])
    }

}else{
  // 单选/判断
  setCheck([val])
}
}
// 判断对错
const checkAns = () =>{
  console.log(data.answer);
  console.log(ischeck.sort().join(","));
  let ans = data.answer
  let userans = ischeck.sort().join(",")
  if(ans === userans){
    setmsg("回答正确");
  }else{
    setmsg("回答错误,正确答案是"+ans);
  }
  // 发送请求给后台 记录
  // actionType:"exam_test"
  // categoryCode:"1534654"
  // id:109
  // userAnswer:"A,C"
  // sessionStorage.removeItem("xxx")
  Getput({
    actionType:"exam_test",
    categoryCode:data.categoryCode,
    id:data.id,
    userAnswer:userans
  }).then(res=>{
    console.log(res);
    if(res.errCode===0){
      sessionStorage.removeItem("homedata")
    }else{

    }
  })
}
// 
// 用数组 存储 用户的选项比较方便

// const ischeck = ["A","B"]//用户选了谁
  return (
    <div className='choice'>
      <div className='title'>
        <div className='type'>{questionType[data.questionType]}</div>
        <div className='qtitle'>{data.title}</div>
      </div>
      <div className='option'>
        {
          options.map((item,index)=>{
            return (
               <ChoiceItem 
                key={index}
                data={item}
                ischeck={ischeck.includes(item.key)} oncheck={oncheck}          ></ChoiceItem>
            )
          })
        }
      
       {/* <ChoiceItem></ChoiceItem>
       <ChoiceItem></ChoiceItem>
       <ChoiceItem></ChoiceItem> */}
      </div>
      <div className="btn1" onClick={checkAns}>确定</div>
      {/* <Button variant="contained" >确定</Button> */}
      <div>{Msg}</div>
    </div>
  )
}
